'''
Created on 2013/5/20

@author: cat
'''

"""\
Scan for serial ports. Linux specific variant that also includes USB/Serial
adapters.

Part of pySerial (http://pyserial.sf.net)
(C) 2009 <cliechti@gmx.net>
"""

import serial
import glob
import threading
from ExerciseRecord import RawDataRecord
import time

device_name = []
device_port = []

def scan():
    """scan for available ports. return a list of device names."""
    return glob.glob('/dev/ttyUSB*')

def serial_init():    
    device_name = scan()
    for name in device_name:
        newport = serial.Serial(port = name,
                                baudrate = 9600,
                                parity = serial.PARITY_NONE,
                                stopbits = serial.STOPBITS_ONE,
                                bytesize = serial.EIGHTBITS,
                                timeout = 0.5)
        device_port.append(newport)
        if(newport.isOpen() == False):
            newport.open()
        
        
def serial_clearBuffer(port):
    if port.isOpen():
        port.flushInput()
        port.flushOutput()
        
class Serial_Thread(threading.Thread):
    #_port = None
    #_buffer = []
    #_isHeader = False
    #_isTail = False
    #_rawdata_record = None
    #_point = ""
    #_lock = None
    
    
    def init(self, port, rawdata, point, lock):
        self._port = port
        self._rawdata_record = rawdata
        self._point = point
        self._lock = lock
        self._buffer = ""
        

    def chek_tagid(self, str):
        tagid = 0
        for i in range(8, 24):
            try:
                tagid = tagid * 10 + int(str[i])
            except:
                return -1

        return tagid


    def read_tagid(self, tempData):
        try:
            self._buffer = self._port.readline()
        except:
            #print "timeout error"
            pass
        if len(self._buffer) < 5:
            return
        tid = self.chek_tagid(self._buffer)
        #data.append(RawDataRecord(tid, time.time()))
        if tid != -1:
            tempData[tid] = RawDataRecord(tid, time.time())       
        
        #print data        
        
    def run(self):
        while True:
            if self._port.isOpen() == False:
                
                continue

            #time.sleep(1)
            if True:
                data = {}
                self.read_tagid(data)
                if len(data) == 0:
                    continue

                while self._lock.acquire() == False: 
                    '''
                    for i in range(len(data) - 1):
                        for j in range(1, len(data)):
                            if data[i].tag_id == data[j].tag_id:
                                
                                print "del duplicated tagid %s" %data[i].tag_id
                                del data[j]
                                     '''
                    self.read_tagid(data)
                    #time.sleep(0.5)
                    
                for k, v in data.iteritems():
                    self._rawdata_record.append(v)
                    #print "%s %s" %(k, v)
                    #print "%s : %s" %(self._point, self._rawdata_record)
                self._lock.release()
            #print("not readable")
                    
                    
                    
                       
                